package com.yuntsg.ruiijn.paperana.test;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.*;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.json.JsonData;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.yuntsg.ruiijn.paperana.utils.esutils.EsServerEntityTempNew;
import com.yuntsg.ruiijn.paperana.utils.esutils.IndexConfig;
import common.util.StringUtil;
import lombok.SneakyThrows;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class 测试新数据检索es自建库测试中文 {
    @SneakyThrows
    public static void main(String[] args) throws SQLException {
        // 2024年7月29日14:38:04 新版本入库es 进行查询

        String str = "神经体液因子过度释放及肌节基因突变等";


        // 创建低级客户端
        RestClient restClient = RestClient
                .builder(new HttpHost("127.0.0.1", 9200))
                .setRequestConfigCallback(re -> {
                    re.setConnectTimeout(10000);
                    re.setSocketTimeout(150000);
                    re.setConnectionRequestTimeout(20000);
                    return re;
                })
                .setHttpClientConfigCallback(re -> {
                    re.setMaxConnTotal(1000);
                    re.setMaxConnPerRoute(1000);
                    return re;
                })
                .build();

        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
//        // 创建API客户端
        ElasticsearchClient client = new ElasticsearchClient(transport);
        String esIndex = IndexConfig.SELF_TETX_INDEX;

        //es 检索句子 默认60%
        String txtSimilar = "60%";

        String finalEsSimilar = txtSimilar;
        // 自定义拆分对比也用这个代码
        BoolQuery.Builder allQueryBuilder = new BoolQuery.Builder();
        List<EsServerEntityTempNew> res = new ArrayList<>();
        //全网对比
        Query query = MatchQuery.of(t -> t.field("str").query(str).minimumShouldMatch(finalEsSimilar))._toQuery();
        allQueryBuilder.must(query);
        //  2024年8月2日13:23:59 添加测试过滤pm和ut
        String PMUT = "";
        //需要排出的年份
        Integer checkYear = null;
        if (StringUtil.isNotNull(PMUT)) {
            Query queryPmut = MatchQuery.of(t -> t.field("pmid_ut").query(PMUT))._toQuery();
            allQueryBuilder.mustNot(queryPmut);
        }
        if (StringUtil.isNotNull(checkYear) && checkYear.intValue() > 0) {
            //排除后面的文章 抄袭只能抄袭以前的文章 不能抄袭未来发表的文章 对吧..
            Query rangeQuery = RangeQuery.of(t -> t.field("year").lte(JsonData.of(checkYear)))._toQuery();
            allQueryBuilder.must(rangeQuery);
        }
        String finalIndex = esIndex;
        SearchResponse<EsServerEntityTempNew> response = client.search(s -> s
                        .index(finalIndex)
                        .fields(Arrays.asList(
                                FieldAndFormat.of(builder -> builder.field("file_id")),
                                FieldAndFormat.of(builder -> builder.field("database_type")),
                                FieldAndFormat.of(builder -> builder.field("pmid_ut")),
                                FieldAndFormat.of(builder -> builder.field("year")),
                                FieldAndFormat.of(builder -> builder.field("str")),
                                FieldAndFormat.of(builder -> builder.field("table_id"))))
                        .from(0)
                        .size(10)
                        .highlight(h -> h.preTags("<span style=\"color:red\">").postTags("</span>").fields("str", highlightFieldBuilder -> highlightFieldBuilder))
                        .query(allQueryBuilder.build()._toQuery()),
                EsServerEntityTempNew.class
        );
        List<Hit<EsServerEntityTempNew>> hits = response.hits().hits();
        for (Hit<EsServerEntityTempNew> hit : hits) {
            EsServerEntityTempNew source = hit.source();
            Map<String, List<String>> highlight = hit.highlight();
            StringBuffer news = new StringBuffer();
            highlight.forEach((k, v) -> {
                for (String s : v) {
                    news.append(s + " ");
                }
            });
            source.setESid(hit.id());
            source.setStrMatchRed(news.toString());
            res.add(source);
        }
        System.out.println(res);
//        return res;
//

    }


}
